﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System.ComponentModel;
using BrainTechLLC.ImageOperatorsNonAForgeDependent;
using System.Drawing;
using System.Windows.Threading;
using System.Windows.Media;
using BrainTechLLC;
using BrainTechLLC.WPF;
using BrainTechLLC.ImageOperators;
using System.Windows;
using System;
using System.Threading;
using System.Windows.Media.Imaging;
using System.Diagnostics;

using System.IO;

namespace ImageAppDataModels
{
    public partial class LazyLoadingImageSource
    {
        public static LazyLoader<FileImage> _lazyLoaderImageSource = new LazyLoader<FileImage>(LoadImageSourceAction, true, ThreadPriority.Normal); //ThreadPriority.BelowNormal);

        public static void LoadImageSourceAction(ActionAndCallback<FileImage> fiAction, FileImage fi)
        {
            Bitmap src = null;

            Timing.BeginTiming();
            {
                src = fi.GetTransformedBitmap(Convert.ToInt32(Math.Floor(fi.ImageSourceWidth)), Convert.ToInt32(Math.Floor(fi.ImageSourceHeight)), true);
            }
            Timing.EndTiming((d) => AllStats.GetInstance().AddTime("AverageImageSourceTime", d));

            if (src != null)
            {
                Application.Current.Dispatcher.RunOnDispatcher(new ThreeParamDelegate((o, o2, o3) =>
                {
                    try
                    {
                        var fileImage = o as FileImage;
                        Bitmap bm = o2 as Bitmap;
                        ActionAndCallback<FileImage> fiAct = o3 as ActionAndCallback<FileImage>;

                        if (fileImage._imageSource != null) 
                        {
                            Console.WriteLine(Path.GetFileName(fileImage.FileName) + " does not have a non-null or dirty cached image source");
                        }

                        byte[] bytes = fileImage.ImageBytesCached;
                        ImageSource imgSource = bm.CreateImageSourceFromBitmap(bytes);
                        fileImage.ImageSource = imgSource;
                        Debug.WriteLine("Set Image Source for " + Path.GetFileName(fileImage.FileName));
                        _lazyLoaderImageSource._working.Remove(fiAct);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }),
                DispatcherPriority.Background, //Normal, // should be okay  Background
                fi, src, fiAction);
            }
        }
    }
}
